package com.mark.web.data.util;

import com.mark.common.utils.PropertiesUtil;
import com.mark.common.enums.PropertiesEnum;
import com.mark.web.data.exception.FTPUtilException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * @Description: 上传文件到FTP服务器的工具类
 * @Author: Mark
 * @CreateDate: 2018/3/26.
 * @Version: 2.0
 * @Copyright : 豆浆油条个人非正式工作室
 */
@Slf4j
public class FTPUtil {
    //从配置文件中读取连接FTP的参数
    private static String ftpIp = PropertiesUtil.getProperty(PropertiesEnum.FTP_SERVICE_IP.getPropertiesName());
    private static String ftpUser = PropertiesUtil.getProperty(PropertiesEnum.FTP_USER.getPropertiesName());
    private static String ftpPass = PropertiesUtil.getProperty(PropertiesEnum.FTP_PASS.getPropertiesName());

    private static  String REMOLE_PATH = "img";//上传到远程的路径

    private String ip;
    private static  final int PORT = 21;//默认端口为21
    private String user;
    private String pwd;
    private FTPClient ftpClient;

    public FTPUtil(String ip,String user,String pwd) {
        this.ip = ip;
        this.user = user;
        this.pwd = pwd;
    }

    /**
     * 对外开放的方法接口
     * @param fileList
     * @return 是否上传成功
     * @throws IOException
     */
    public static Boolean uploadFile(List<File> fileList,String remolePath) throws FTPUtilException {
        FTPUtil ftpUtil = new FTPUtil(ftpIp,ftpUser,ftpPass);
        log.info("开始连接FTP服务器");
        if(StringUtils.isNotBlank(remolePath)){
            REMOLE_PATH = remolePath;
        }
        boolean result = ftpUtil.uploadFile(REMOLE_PATH,fileList);
        log.info("结束上传,上传结果:{}",result);
        return result;
    }

    //上传文件的具体实现
    private boolean uploadFile(String remotePath, List<File> fileList) throws FTPUtilException {
        boolean uploaded  = true;
        FileInputStream fis = null;
        if(connectServer(this.ip,this.user,this.pwd)){//FTP的连接
            try {
               /*
                Boolean flag = true;
                String[] dirs = "img/campus2".split("/");
                ftpClient.changeWorkingDirectory("/");//切换回根目录

                for(int i = 0; dirs!=null && i < dirs.length ;i++){
                    if (!ftpClient.changeWorkingDirectory(dirs[i])){//如果不能切换到该目录就创建
                        if(ftpClient.makeDirectory(dirs[i])){
                            if(!ftpClient.changeWorkingDirectory(dirs[i])){
                                flag = false;
                            }
                        }else{
                            flag = false;
                        }
                    }
                }*/

                ftpClient.changeWorkingDirectory(remotePath);//更改工作目录
                ftpClient.setBufferSize(1024);//设置缓冲区
                ftpClient.setControlEncoding("UTF-8");
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//文件类型设置为二进制（放置乱码）
                ftpClient.enterLocalPassiveMode();//打开本地被动模式
                for (File fileItem : fileList){
                    fis = new FileInputStream(fileItem);
                    ftpClient.storeFile(fileItem.getName(),fis);//存储文件
                }
            } catch (IOException e) {
                log.error("上传文件异常",e.getMessage());
                uploaded = false;
                throw new FTPUtilException(e.getMessage());
            }finally {//释放连接
                try {
                    fis.close();
                    ftpClient.disconnect();
                } catch (IOException e) {
                    log.error("关闭资源异常：{}",e.getMessage());
                }
            }
        }else{
            uploaded =false;
        }
        return uploaded;
    }

    //连接FTP服务器
    private boolean connectServer(String ip, String user, String pwd) {
        boolean isSuccess = false;
        ftpClient = new FTPClient();
        try {
            ftpClient.connect(ip,PORT);
            isSuccess = ftpClient.login(user,pwd);
            if(isSuccess){
                log.info("已成功连登录上FTP服务器");
            }
        } catch (IOException e) {
            log.error("连接FTP服务器异常:{}",e.getMessage());
        }
        return isSuccess;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public FTPClient getFtpClient() {
        return ftpClient;
    }

    public void setFtpClient(FTPClient ftpClient) {
        this.ftpClient = ftpClient;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
}
